﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Axis.BusinessObject.Product;
using Axis.Dao.Product;

namespace Sotipha.Web.Views.Cart
{
    public partial class Default : CPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ProductID"] != null && Request.QueryString["Quality"] != null)
            {
                InsertCart(Request.QueryString["ProductID"].ToString(), Request.QueryString["Quality"].ToString());
            }
            if (Request.QueryString["RemoveID"] != null)
            {
                RemoveCart(Request.QueryString["RemoveID"].ToString());
            }

            String cartDetail = "";
            String cartTotal = "";
            ShowCart(ref cartDetail, ref cartTotal);

            ltrCart.Text = cartDetail;
            ltrTotal.Text = cartTotal;


            //POST
            if (Request.Form["ID"] != null && Request.Form["num"] != null)
            {
                UpdateCart(Request.Form["ID"].ToString(), Request.Form["num"].ToString());
                ShowCart(ref cartDetail, ref cartTotal);
                Response.Write(cartTotal);
                Response.End();
            }

            if (Session["lang"].ToString() == "vi")
            {
                ltrAddress.Text = "Địa chỉ";
                ltrFullname.Text = "Họ tên";
                ltrPhone.Text = "Điện thoại";
                ltrShoppingBag.Text = "Giỏ Hàng";
            }
            if (Session["CustomerName"] != null)
            {
                txtName.Text = Session["CustomerName"].ToString();
                txtPhone.Text = Session["Phone"].ToString();
                txtAddress.Text = Session["Address"].ToString();
                txtEmail.Text = Session["Email"].ToString();
            }
        }

        private void UpdateCart(string IdRe, string numRe)
        {
            int id = -1;
            int num = -1;
            //throw new NotImplementedException();//
            try
            {
                id = int.Parse(IdRe);
                num = int.Parse(numRe);

                var items = (List<ShoppingCart>)Session["ShoppingCart"];
                var cur = (from i in items where i.product.ID == id select i).SingleOrDefault();
                if (cur != null)
                {
                    cur.quality = num;
                }
                Session["ShoppingCart"] = items;


            }
            catch { }
        }

        private void RemoveCart(string p)
        {
            int id = -1;
            try
            {
                id = int.Parse(p);
                var items = (List<ShoppingCart>)Session["ShoppingCart"];
                items.Remove((from i in items where i.product.ID == id select i).SingleOrDefault());
                if (items.Count > 0)
                {
                    for (int i = 0; i < items.Count; i++)
                    {
                        items[i].idx = i + 1;
                    }
                }
                Session["ShoppingCart"] = items;
            }
            catch
            {
            }

        }

        public void ShowCart(ref  String cartDetail, ref string totalCart)
        {
            String header = "<table cellspacing=\"0\" cellpadding=\"0\"><tr><th width=\"20px\"></th>" +
                            "<th width=\"120px\">{0}</th><th class=\"tt\">{1}</th>" +
                            "<th>{2}</th><th>{3}</th><th></th></tr>";

            String contentPatern = "<tr><td>{0}</td><td><a href=\"{1}\"><img src=\"{2}\" /></a></td><td class=\"tt\">" +
                                   "<a href=\"{3}\">{4}</a></td><td><input id='input_item_{5}' value=\"{6}\" onchange=\"return changeQuanlity('{5}')\" /></td><td>{7}</td><td> " +
                                   "<a href=\"{8}\"><img src=\"../../../images/Delete.png\"  class=\"ActionDel\" " +
                                   " /></a></td></tr>";
            String footer = "</table>";

            var items = (List<ShoppingCart>)Session["ShoppingCart"];
            String table = "";
            double total = 0;
            #region "En"
            if (Session["lang"].ToString() == "en")
            {
                table = String.Format(header, "Product Image", "Product Name", "Quantity", "Price");
                if (items != null)
                {
                    foreach (var shoppingCart in items)
                    {
                        var link = "#";
                        var delLink = "Default.aspx?RemoveID=" + shoppingCart.product.ID;
                        var price = String.Format("{0:0,0}", shoppingCart.product.Price) + "VND";
                        table += String.Format(contentPatern, shoppingCart.idx, link, shoppingCart.product.Thumbnail, link,
                                               shoppingCart.product.Name_VN, shoppingCart.product.ID,
                                               shoppingCart.quality, price, delLink);
                        total += shoppingCart.quality * shoppingCart.product.Price;

                    }
                }
                else
                {
                    table += "<tr><td colspan=\"6\">No product in your cart</td></tr>";
                }
                totalCart = String.Format("<label>Total price:</label><span>{0}VND</span>", String.Format("{0:0,0}", total));
            }
            #endregion

            #region "Vi"



            else if (Session["lang"].ToString() == "vi")
            {
                table = String.Format(header, "Hình ảnh", "Tên sản phẩm", "Số lượng", "Giá");
                if (items != null)
                {
                    foreach (var shoppingCart in items)
                    {
                        var link = "#";
                        var delLink = "Default.aspx?RemoveID=" + shoppingCart.product.ID;
                        var price = String.Format("{0:0,0}", shoppingCart.product.Price) + "VNĐ";
                        table += String.Format(contentPatern, shoppingCart.idx, link, shoppingCart.product.Thumbnail, link,
                                               shoppingCart.product.Name_VN, "input_item_" + shoppingCart.product.ID,
                                               shoppingCart.quality, price, delLink);
                        total += shoppingCart.quality * shoppingCart.product.Price;
                    }
                }
                else
                {
                    table += "<tr><td colspan=\"6\">Không có sản phẩm nào trong giỏ hàng</td></tr>";
                }
                totalCart = String.Format("<label>Tổng tiền:</label><span>{0}VNĐ</span>", String.Format("{0:0,0} ", total));
            }
            #endregion
            table += footer;

            cartDetail = table;
        }

        private void InsertCart(String productId, String quality)
        {
            int ID = int.Parse(productId);
            int num = int.Parse(quality);
            ShoppingCart newItem = null;

            CProductDao dao = new CProductDao();

            List<ShoppingCart> items = null;

            var inputValue = string.Format("<InputValue ID=\"{0}\" Context =\"Detail\"/>", ID);
            IList<CProduct> product = dao.GetProduct(inputValue);
            if (product != null && product.Count > 0)
            {
                newItem = new ShoppingCart();
                newItem.product = product[0];
                newItem.quality = num;
            }
            else
            {
                return;
            }

            if (Session["ShoppingCart"] == null)
            {
                newItem.idx = 1;
                items = new List<ShoppingCart>();
                items.Add(newItem);
            }
            else
            {
                items = (List<ShoppingCart>)Session["ShoppingCart"];
                var existItem = (from i in items where i.product.ID == ID select i).SingleOrDefault();
                if (existItem != null)
                {
                    existItem.quality = existItem.quality + newItem.quality;
                }
                else
                {
                    newItem.idx = items.Count + 1;
                    items.Add(newItem);
                }
            }
            Session["ShoppingCart"] = items;
        }
    }

    public class ShoppingCart
    {
        public int idx { get; set; }
        public CProduct product { get; set; }
        public int quality { get; set; }
    }
}